package com.agp.service.impl;

import com.agp.dto.*;
import com.agp.entity.AncientTree;
import com.agp.entity.HealthRecord;
import com.agp.entity.Position;
import com.agp.mapper.TreeMapper;
import com.agp.mapper.TreeMediaMapper;
import com.agp.result.PageResult;
import com.agp.service.TreeService;
import com.agp.vo.*;
import com.agp.websocket.WebSocketServer;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.util.*;

/**
 * 古树业务层
 */
@Service
@Slf4j
public class TreeServiceImpl implements TreeService {
    @Autowired
    private TreeMapper treeMapper;
    @Autowired
    private TreeMediaMapper treeMediaMapper;
    @Autowired
    private WebSocketServer webSocketServer;


    // 添加古树
    @Override
    public Integer save(TreeDTO treeDTO) throws Exception {
        AncientTree tree = new AncientTree();
        // 属性复制
        BeanUtils.copyProperties(treeDTO, tree);

        tree.setCreateTime(LocalDateTime.now());
        tree.setUpdateTime(LocalDateTime.now());
        // treeMapper.insert(tree);
        return 1;


    }

    // 古树分页查询
    @Override
    public PageResult page(AncientTreePageQueryDTO pageQueryDTO) {
        PageHelper.startPage(pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
        Page<AncientTree> page = treeMapper.page(pageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }


    /**
     * 获取所有古树标记所需要信息
     *
     * @return
     */
    @Override
    public List<MarkerVO> getMarker() {

        // 查询古树标记所需要信息除图片地址
        List<AncientTree> ancientTreeList = treeMapper.selectMarker();

        List<MarkerVO> markerVOList = new ArrayList<>();

        // 查询古树标记所需要图片地址
        for (AncientTree item : ancientTreeList) {
            MarkerVO markerVO = new MarkerVO();

            String treeMediaUrl = treeMediaMapper.selectByTreeId(item.getTreeId());
            BeanUtils.copyProperties(item, markerVO); // 属性拷贝
            markerVO.setPosition(new Position(item.getGpsLongitude(), item.getGpsLatitude()));
            markerVO.setMediaUrl(treeMediaUrl);
            Integer healthStatus = treeMapper.selectHealthStatus(item.getTreeId());
            markerVO.setHealthStatus(healthStatus);
            markerVOList.add(markerVO);
        }
        return markerVOList;

    }

    //  古树删除业务
    @Override
    public void delete(Integer[] ids) {

        if (ids == null || ids.length == 0) {
            throw new IllegalArgumentException("删除ID数组不能为空");
        }
        Integer count = treeMapper.delete(ids);
        if (count <= 0) {
            log.info("删除失败,id不存在");
        } else {
            log.info("成功删除 {} 条古树数据", count);
        }


    }

    // 古树更新业务
    @Override
    public void update(TreeUpdateDTO treeUpdateDTO) {
        if (treeUpdateDTO.getTreeId() == null) {
            throw new IllegalArgumentException("古树ID不能为空");
        }
        treeMapper.update(treeUpdateDTO);
    }

    /**
     * 获取古树科名数量
     *
     * @return
     */
    @Override
    public List<TreeFamilyCountVO> getTreeFamilyCount() {
        List<TreeFamilyCountVO> treeFamilyCountVOList = treeMapper.selectTreeFamilyCount();
        return treeFamilyCountVOList;
    }

    /**
     * 获取古树属名数量
     *
     * @return
     */
    @Override
    public List<TreeGenusCountVO> getTreeGenusCount() {
        List<TreeGenusCountVO> treeGenusCountVOList = treeMapper.selectTreeGenusCount();
        return treeGenusCountVOList;
    }

    /**
     * 添加健康记录
     *
     * @param healthRecordDTO
     * @return
     */
    @Override
    public void addHealthyRecord(HealthRecordDTO healthRecordDTO) throws JsonProcessingException {
        HealthRecord healthRecord = new HealthRecord();

        BeanUtils.copyProperties(healthRecordDTO, healthRecord);

        ObjectMapper objectMapper = new ObjectMapper();
        String photoUrlsJson = objectMapper.writeValueAsString(healthRecordDTO.getPhotoUrls());

        healthRecord.setPhotoUrls(photoUrlsJson);

        healthRecord.setCheckDate(OffsetDateTime.now());
        treeMapper.insertHealthyRecord(healthRecord);
        // 通过WebSocket向客户端浏览器推送消息
        Map map = new HashMap();
        map.put("recordId", healthRecord.getRecordId());
        map.put("treeId", healthRecord.getTreeId());

        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }


    /**
     * 获取古树详情信息
     *
     * @param treeId
     * @return
     */
    @Override
    public TreeDetailVO getDetailTreeInfo(Integer treeId) {
        TreeDetailVO treeDetailVO = new TreeDetailVO();
        AncientTree tree = treeMapper.getTreeById(treeId);
        BeanUtils.copyProperties(tree, treeDetailVO);
        // 查询图片
        List<String> treeMediaList = treeMediaMapper.selectByTreeIdList(treeId);
        treeDetailVO.setImages(treeMediaList);
        return treeDetailVO;
    }

    /**
     * 获取古树健康记录
     *
     * @param
     * @return
     */
    @Override
    public List<MessageVO> getHealthyRecord(MessageQueryDTO messageQueryDTO) {
        List<HealthRecord> healthRecordList = treeMapper.getHealthyRecord(messageQueryDTO);

        List<MessageVO> messageVOList = new ArrayList<>();

        for (HealthRecord healthRecord : healthRecordList) {
            MessageVO  messageVO = new MessageVO();
            BeanUtils.copyProperties(healthRecord, messageVO);


            ObjectMapper objectMapper = new ObjectMapper();
            try {
                String photoUrlsJson = healthRecord.getPhotoUrls();
                if (photoUrlsJson == null || photoUrlsJson.trim().isEmpty()) {
                    messageVO.setPhotoUrls(Collections.emptyList());

                } else {
                    List<String> photoUrls = objectMapper.readValue(photoUrlsJson, new TypeReference<List<String>>() {});
                    messageVO.setPhotoUrls(photoUrls);

                }
            } catch (Exception e) {
                // 可记录日志或设置为空列表
               throw  new RuntimeException("JSON解析异常");
            }
            messageVOList.add(messageVO);
        }
        return messageVOList;
    }

    /**
     * 更新健康记录状态
     *
     * @param healthRecord
     */
    @Override
    public void updateHealthRecordStatus(HealthRecord healthRecord) {
        treeMapper.updateHealthRecordStatus(healthRecord);

    }


}
